package com.xhgd.order.service.impl;


import com.xhgd.order.service.OrderService;
import com.xhgd.order.model.bean.Order;
import com.xhgd.product.model.bean.Product;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;

@Slf4j
@Service
public class OrderServerImpl implements OrderService {

    @Autowired
    DiscoveryClient discoveryClient;
    @Autowired
    RestTemplate restTemplate;
    @Autowired //导入spring-cloud的loadBalancer
    LoadBalancerClient loadBalancerClient;

    @Override
    public Order createOrder(Long productId, Long userId) {
        Product product = getProductFromRemoteWithLoadBalanceAnnotation(productId);
        Order order = new Order();
        order.setId(1L);
        //总金额的获取
        order.setTotalAmount( product.getPrice().multiply(new BigDecimal(product.getNum())));
        order.setUserId(userId);
        order.setNikcName("zhangsan");
        order.setAddress("协和光电");
        //todo:远程获取商品的列表
        order.setProductList(Arrays.asList(product) );
        return order;
    }
    private Product getProductFromRemoteWithLoadBalance(Long productId) {
        ServiceInstance choose = loadBalancerClient.choose("service-product");
        String url = "http://" + choose.getHost() + ":" + choose.getPort()+"/product/"+ productId;
        log.info("远程请求：{}",  url);
        Product product = restTemplate.getForObject(url, Product.class);
        return product;
    }

    private Product getProductFromRemote(Long productId) {
        List<ServiceInstance> instances = discoveryClient.getInstances("service-product");
        ServiceInstance instance = instances.get(0);
        String url = "http://" + instance.getHost() + ":" + instance.getPort()+"/product/"+ productId;
        log.info("远程请求：{}",  url);
        Product product = restTemplate.getForObject(url, Product.class);
        return product;
    }
 //基于注解的远程调用，最简单最方便，直接在restTemplate中添加@LoadBalanced注解
    private Product getProductFromRemoteWithLoadBalanceAnnotation(Long productId) {

        String url = "http://service-product/product/"+productId;
        log.info("远程请求：{}",  url);
        Product product = restTemplate.getForObject(url, Product.class);
        return product;
    }

}
